/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cz.dnk.android.gug.antilapka;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.telephony.gsm.SmsManager;
import android.telephony.gsm.SmsMessage;
import android.util.Log;

/**
 * Třída receiveru reagující na příchozí SMS
 * 
 * Texty SMS si uživatel volí v nastavení aplikace
 * 
 * 
 * @author jirka
 *
 */
public class SmsFilterReceiver extends BroadcastReceiver {

	private SharedPreferences mSharedPreferences;
	private boolean sSMS;
	private String sAlarmSMS;
	private String sLocSMS;
	
	@Override
	public void onReceive(Context context, Intent intent) {
		/// Načteme uživatelská nastavení
		mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
		
		/// Je povoleno ovládání přes SMS?
		sSMS = mSharedPreferences.getBoolean(
				"pref_SMS", false);
		Log.d("5", "Načitam...");
		/// SMS pro alarm
		sAlarmSMS = mSharedPreferences.getString(
				"pref_Alarm_SMS", null);
		Log.d("6", "Načitam...");
		///SMS pro polohu
		sLocSMS = mSharedPreferences.getString(
				"pref_Loc_SMS", null);
		Log.d("Ende", "Načitam...");
		
		if(!sSMS || (sAlarmSMS == "") || (sLocSMS == "")) {
			/// Nechtějí nás, končíme
			return;
		}
		
		// Zaznam do logu o tom, ze se vubec neco stalo
		Log.i(this.getClass().getSimpleName(),"Prijata sms");

		Bundle bundle = intent.getExtras();
        if (bundle != null) {
        	// Vystupni buffer pro postaveni cele sms
    		StringBuffer sb = new StringBuffer();
    		
        	// PDU = Protocol Data Unit
            Object[] pdusObj = (Object[]) bundle.get("pdus");
            
            // Preklad jednotlivych pod-zprav
            SmsMessage[] messages = new SmsMessage[pdusObj.length]; 
            for (int i = 0; i < pdusObj.length; i++) { 
                messages[i] = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
                sb.append(messages[i].getMessageBody());
            }

            // V pripade SMS zacinajici lokačním textem
            if (sb.toString().startsWith(sLocSMS)) {
            	
/*            	// nicmene takto by vypadal kod pro ziskani aktualni pozice
         	    LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
            	Location l = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            	
            	int lat6E = (int) (location.getLatitude() * 1000000);
            	int lon6E = (int) (location.getLongitude() * 1000000);
*/           	
            	
            	int lat6E = 50110437;
            	int lon6E = 14501513;
           	
            	String smsText = "Aktualní pozice telefonu: " + lon6E + "," + lat6E;
            	// Pro snazsi ladeni si poznamename text sms do logu
            	Log.i(getClass().getSimpleName(),smsText);
            	
            	// Zpravu posleme na cislo, ktere poslalo lokalizacni SMS
            	String nr = messages[0].getOriginatingAddress();

            	// Odeslani sms
            	SmsManager.getDefault().sendTextMessage(nr, null, smsText, null, null);

            }
            
            // Když se po nás chce alarm 
            if (sb.toString().startsWith(sAlarmSMS)) {
            	/// Zavoláme si službu a odpálíme alarm
            	Log.d("","Došla SMS, Pálím alarm");
            	context.startService(new Intent(context, AntiLapkaService.class).putExtra("cz.dnk.gug.android.antilapka.Fire", true));
            }
        }
	}
}